<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="起始地" prop="departureId">
        <el-input
          v-model="queryParams.departureId"
          placeholder="请输入起始地"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="目的地" prop="destinationId">
        <el-input
          v-model="queryParams.destinationId"
          placeholder="请输入目的地"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="运输类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择运输类型" clearable>
          <el-option
            v-for="(dict,index) in dict.type.transport_task_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="总重量" prop="weight">
        <el-input
          v-model="queryParams.weight"
          placeholder="请输入总重量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="运输状态" prop="state">
        <el-input
          v-model="queryParams.state"
          placeholder="请输入运输状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 205px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间">
        <el-date-picker
          v-model="daterangeUpdateTime"
          style="width: 205px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['transport:task:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['transport:task:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['transport:task:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['transport:task:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="起始地" align="center" prop="departureId" width="200">
        <template slot-scope="scope">
          {{scope.row.departureDistrict+scope.row.departureTown+scope.row.departureWarehouseName}}
        </template>
      </el-table-column>
      <el-table-column label="目的地" align="center" prop="destinationId" width="200">
        <template slot-scope="scope">
          {{scope.row.destinationDistrict+scope.row.destinationTown+scope.row.destinationWarehouseName}}
        </template>
      </el-table-column>
      <el-table-column label="运输类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.transport_task_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="总重量" align="center" prop="weight" />
      <el-table-column label="运输状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.transport_task_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['transport:task:assign']"
            v-if="scope.row.state === 0"
          >打包</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="updateMessage(scope.row)"
            v-hasPermi="['transport:task:edit']"
            v-if="scope.row.state === 0"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['transport:task:remove']"
            v-if="scope.row.state === 0"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或分配运输任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" :width="title === '分配运输任务'? '800px' : '500px'" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 当为新增任务之时才会显现 -->
        <el-form-item label="起始地" prop="departureId" placeholder="请输入起始地" v-if="title === '添加运输任务'">
          <el-select v-model="form.departureId" clearable @change="selectWarehouse" style="width: 100%">
            <el-option v-for="(dict,index) in warehousesList"
              :key="dict.warehouseId"
              :label="`${dict.district}${dict.town}${dict.warehouseName}`"
              :value="dict.warehouseId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目的地" prop="destinationId" placeholder="请输入目的地" v-if="title === '添加运输任务'">
          <el-select v-model="form.destinationId" clearable @change="selectWarehouse" style="width: 100%">
            <el-option v-for="(dict,index) in warehousesList"
                       :key="dict.warehouseId"
                       :label="`${dict.district}${dict.town}${dict.warehouseName}`"
                       :value="dict.warehouseId">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 修改运输任务时该有的内容 -->
        <el-form-item label="起始地" placeholder="请输入起始地" v-if="title === '修改运输任务'">
          <el-select v-model="departure" clearable @change="selectChangeDeparture" style="width: 100%">
            <el-option v-for="(dict,index) in warehousesList"
                       :key="dict.warehouseId"
                       :label="`${dict.district}${dict.town}${dict.warehouseName}`"
                       :value="dict.warehouseId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目的地" placeholder="请输入目的地" v-if="title === '修改运输任务'">
          <el-select v-model="destination" clearable @change="selectChangeDestination" style="width: 100%">
            <el-option v-for="(dict,index) in warehousesList"
                       :key="dict.warehouseId"
                       :label="`${dict.district}${dict.town}${dict.warehouseName}`"
                       :value="dict.warehouseId">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 当为内部运输的时候才会显现 -->
        <el-form-item label="运输类型" prop="type" v-if="title === '添加运输任务' || title === '修改运输任务'">
          <el-select v-model="form.type" placeholder="请选择运输类型" style="width: 100%">
            <el-option
              v-for="(dict,index) in dict.type.transport_task_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 内部运输时选择车辆 -->
      <template v-if="title === '分配运输任务'">
        <div style="display: flex;justify-content: center" v-if="transportType === 1">
          <span style="font-size: 18px;line-height: 40px">运输车辆：</span>
          <el-select
            v-model="carDriver" placeholder="请选择车辆" style="width: 60%;margin-bottom: 20px" clearable>
            <el-option
              v-for="(dict,index) in carList"
              :key="dict.vehicleId"
              :label="`${dict.model}-${dict.vehicleNumber}`"
              :value="dict.vehicleId"
              clearable>
            </el-option>
          </el-select>
        </div>

        <!-- 当为外部运输时才会显现 -->
        <el-form ref="elForm" :model="formData" label-width="80px" v-if="transportType === 2">
          <el-row>
            <el-col :span="12">
              <el-form-item label="生产商" prop="manufacturer">
                <el-input v-model="formData.manufacturer" placeholder="请输入生产商"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车辆型号" prop="model">
                <el-input v-model="formData.model" placeholder="请输入车辆型号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="车牌号" prop="vehicleNumber">
                <el-input v-model="formData.vehicleNumber" placeholder="请输入车牌号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车辆载重" prop="capacity">
                <el-input v-model="formData.capacity" placeholder="请输入车辆载重"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="运输公司" prop="companyId">
                <el-select v-model="formData.companyId" placeholder="请选择物流公司" clearable :style="{width: '100%'}">
                  <el-option
                    v-for="(item,index) in companyList"
                    :key="item.companyId"
                    :label="item.companyName"
                    :value="item.companyId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="运费" prop="salary">
                <el-input v-model="formData.salary" placeholder="请输入车辆运费"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: center" v-if="title === '分配运输任务'">
          <el-transfer
            style="text-align: left; display: inline-block"
            v-model="orderList"
            :titles="['未发货', '打包发货']"
            :render-content="renderFunc"
            :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'}"
            @change="handleChange"
            :data="allValue">
          </el-transfer>
        </div>
      </template>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitChange" v-if="title === '修改运输任务'">确 定</el-button>
        <el-button type="primary" @click="submitForm" v-else>确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, listWarehouse, listUnAssignTask, listCar, assignTask, getTransportCompanyList, getTaskInfo } from "@/api/transport/task";

export default {
  name: "Task",
  dicts: ['transport_task_type','transport_task_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运输任务表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 运输状态时间范围
      daterangeCreateTime: [],
      // 运输状态时间范围
      daterangeUpdateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        managerId: null,
        departureId: null,
        destinationId: null,
        type: null,
        weight: null,
        state: null,
        createTime: null,
        updateTime: null,
      },
      // 表单参数
      form: {},
      //可选的仓库列表
      warehousesList: [],
      //全部的仓库列表
      allhousesList:[],
      //表示是全部的数据
      allValue : [],
      leftValue: [],
      rightValue: [],
      //将要进行运输的订单
      orderList:[],
      //可用车的列表
      carList:[],
      //送货的司机
      carDriver:'',
      //任务单
      taskID:'',
      //运输公司的列表
      companyList:[],
      //运输的类型
      transportType:'',
      //运输公司
      transportCompany:'',
      // 表单校验
      rules: {
        departureId: [
          { required: true, message: "起始地不能为空", trigger: "blur" }
        ],
        destinationId: [
          { required: true, message: "目的地不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "运输类型不能为空", trigger: "change" }
        ]
      },
      //修改运输单时起点的名称
      departure: '',
      //修改运输单时终点的名称
      destination: '',
      formData: {
        manufacturer: '',
        model: '',
        vehicleNumber: '',
        capacity: '',
        companyId: '',
        salary: ''
      },
    };
  },
  created() {
    this.getList();
  },

  methods: {
    /** 查询运输任务列表 */
    async getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' !== this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      if (null != this.daterangeUpdateTime && '' !== this.daterangeUpdateTime) {
        this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
        this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
      }
      await listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.warehousesList = []
      this.allValue = []
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        taskId: null,
        managerId: null,
        departureId: '',
        destinationId: '',
        type: null,
        weight: null,
        state: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.daterangeUpdateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    async handleAdd() {
      const data = {
        pageNum: 1,
        pageSize: 20
      }
      await listWarehouse(data).then(res => {
        this.warehousesList = res.data
        this.allhousesList = res.data
      })
      this.reset();
      this.open = true;
      this.title = "添加运输任务";
    },

    //修改运输列表
    async updateMessage(row){
      this.transportType = row.type
      await getTaskInfo(row.taskId).then(res => {
        this.form = res.data
        this.departure = this.form.departureDistrict+this.form.departureTown+this.form.departureWarehouseName
        this.destination = this.form.destinationDistrict+this.form.destinationTown+this.form.destinationWarehouseName
      })
      const data = {
        pageNum: 1,
        pageSize: 20
      }
      await listWarehouse(data).then(res => {
        this.allhousesList = res.data
      })
      this.getUnusedWarehouseList()
      this.open = true;
      this.title = "修改运输任务";
    },

    /** 分配按钮操作 */
    handleUpdate(row) {
      this.reset();
      //判断是内部运输还是外部运输
      this.transportType = row.type
      if (this.transportType === 1){
        listCar().then(respond => {
          console.log(123)
          this.carList = respond.data
        })
      }else{
        getTransportCompanyList().then(respond => {
          this.companyList = respond.data
        })
      }
      listUnAssignTask().then(respond => {
        let tempValue = respond.data
        tempValue.forEach(item => {
          this.allValue.push({
            key: item.orderId,
            label : item.departureDistrict+item.departureTown+item.departureAddress+'→'+item.destinationDistrict+item.destinationTown+item.destinationAddress,
            value: item.orderId
          })
        })
      })
      this.taskID = row.taskId
      const taskId = row.taskId || this.ids
      getTask(taskId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "分配运输任务";
      });
    },

    //时刻监控着添加运输任务时出发地和终点的变化,进而将选中的仓库进行剔除
    selectWarehouse(){
      this.warehousesList = []
      this.allhousesList.forEach(item => {
        if (item.warehouseId !== this.form.departureId && item.warehouseId !== this.form.destinationId){
          this.warehousesList.push(item)
        }
      })
    },

    //为修改任务的时候提供的方法，这样为了能够时刻掌握能够使用的仓库
    selectChangeDeparture(){
      this.warehousesList = []
      this.form.departureId = this.departure
      this.getUnusedWarehouseList()
    },
    selectChangeDestination(){
      this.warehousesList = []
      this.form.destinationId = this.destination
      this.getUnusedWarehouseList()
    },
    getUnusedWarehouseList(){
      this.allhousesList.forEach(item => {
        if (item.warehouseId !== this.form.departureId && item.warehouseId !== this.form.destinationId){
          this.warehousesList.push(item)
        }
      })
    },

    //分配此次运输任务的货物
    handleChange(value, direction, movedKeys) {
      if (direction === "right") {
        movedKeys.forEach((key) => {
          let index = this.leftValue.findIndex((item) => item === key);
          this.leftValue.splice(index, 1);
        });
        movedKeys.forEach((key) => {
          this.rightValue.push(key);
        });
      } else {
        movedKeys.forEach((key) => {
          let index = this.rightValue.findIndex((item) => item === key);
          this.rightValue.splice(index, 1);
        });
        movedKeys.forEach((key) => {
          this.leftValue.push(key);
        });
      }
    },

    submitChange(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.taskId != null) {
            let data = {
              taskId: this.form.taskId,
              departureId: this.form.departureId,
              destinationId: this.form.destinationId,
              type: this.form.type
            }
            updateTask(data).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.form = []
              this.open = false
              this.departure = ''
              this.destination = ''
              this.getList()
            })
          }
        }
      })
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.taskId != null) {
            let data = {}
            if (this.transportType === 1){
              data = {
                taskId: this.taskID,
                vehicleId: this.carDriver,
                orderIds: this.rightValue
              }
            }else {
              data = {
                taskId: this.taskID,
                vehicleNumber: this.formData.vehicleNumber,
                model: this.formData.model,
                capacity:this.formData.capacity,
                manufacturer:this.formData.manufacturer,
                companyId: this.formData.companyId,
                orderIds: this.rightValue,
                salary: this.formData.salary
              }
            }
            assignTask(data).then(respond => {
              this.$modal.msgSuccess('分配成功')

              //将数据复原，防止污染下一操作
              this.open = false
              this.taskID = ''
              this.allValue = []
              this.carList = []
              this.carDriver = ''
              this.transportType = ''
              this.transportCompany = ''
              this.companyList = []
              this.formData = {}
              this.getList()
            })
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids;
      this.$modal.confirm('是否确认删除运输任务编号为"' + taskIds + '"的数据项？').then(function() {
        return delTask(taskIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('transport/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    },
    renderFunc(h,option){
      return <span title={option.label}>{option.label}</span>
    }
  }
};
</script>
